package com.pro.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.pro.entity.User;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：刘弘禹
 * @description：TODO
 * @date ：2021/12/26 21:52
 * 自定义UserDetails对象
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    //存储用户权限信息
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    //获取权限信息
    //登录时会把LoginUser对象存在redis缓存当中这个集合由于redis的安全问题不会让其序列化会爆出错误信息，
    //所以将它通过注解来忽略序列化
    @JSONField(serialize = false)
    private static List<SimpleGrantedAuthority> collect = null;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(collect != null){
            return collect;
        }
            //把permissions中的String类型的权限信息封装成SimpleGrantedAuthority对象
            collect = permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
            return collect;
    }
    //获取密码
    @Override
    public String getPassword() {
        return user.getPassword();
    }
    //获取用户账号
    @Override
    public String getUsername() {
        return user.getAccount();
    }
    //判断是否没过期
    @Override
    public boolean isAccountNonExpired() { return true; }
    @Override
    public boolean isAccountNonLocked() { return true; }
    //是否没有超时
    @Override
    public boolean isCredentialsNonExpired() { return true; }
    //判断用户是否可用
    @Override
    public boolean isEnabled() { return true; }
}
